package com.example.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.example.MyEnum.NumberConstant;
import com.example.Utility.Result;
import com.example.entity.OrderMessage;
import com.example.entity.UserAddress;
import com.example.entity.lordOrder;
import com.example.entity.smallEntity.orderMsgDate;
import com.example.service.OrderMessageSrvice;
import com.example.service.UserAddressService;
import com.example.service.lordOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/ordermessage")
public class OrderMessageController {
    @Resource
    private OrderMessageSrvice orderMessageSrvice;
    @Autowired
    private lordOrderService lordOrderService;

    @Autowired
    private UserAddressService userAddressService;

    @Transactional
    @PostMapping("/orderList")
    public Result orderLists(@RequestBody OrderMessage date) {
        // 当前用户的所有订单
        final List<lordOrder> lordOrderList = lordOrderService.list(
                Wrappers.lambdaQuery(lordOrder.class)
                        .eq(lordOrder::getOpenid, date.getOpenid())
                        .orderByDesc(lordOrder::getCreateTime)
        );
        // Classify orders based on their state
        Map<Integer, List<lordOrder>> ordersByState = lordOrderList.stream().collect(Collectors.groupingBy(lordOrder::getState));

        // Fetch order messages and address details for each order
        ordersByState.values().forEach(orders -> {
            List<OrderMessage> orderMessages = orderMessageSrvice.list(Wrappers.lambdaQuery(OrderMessage.class)
                    .in(OrderMessage::getMId, orders.stream().map(lordOrder::getId).toArray()));

            List<Integer> addressIds = orders.stream().map(lordOrder::getAddressId).distinct().collect(Collectors.toList());
            Map<Long, UserAddress> addressesById = userAddressService.listByIds(addressIds).stream()
                    .collect(Collectors.toMap(UserAddress::getId, Function.identity()));
            orders.forEach(order -> {
                order.setOrderMessages(orderMessages.stream()
                        .filter(m -> m.getMId().equals(order.getId()))
                        .collect(Collectors.toList()));
                order.setAddressMsg(addressesById.get(order.getAddressId()));
            });
        });
        // Construct and return the response object
        orderMsgDate orderMsgDate = new orderMsgDate(
                ordersByState.getOrDefault(NumberConstant.ZERO, Collections.emptyList()),
                ordersByState.getOrDefault(NumberConstant.ONE, Collections.emptyList()),
                ordersByState.getOrDefault(NumberConstant.TWO, Collections.emptyList()),
                ordersByState.getOrDefault(NumberConstant.THREE, Collections.emptyList()),
                lordOrderList);
        return Result.succeed(orderMsgDate);
    }


    /**
     * 订单详情页
     */

    @GetMapping("getOrderIntroducePage")
    public Result getOrderIntroducePage(@RequestParam("Mid") Integer Mid) {
        //根据用户MID 获取订单详情
        LambdaQueryWrapper<lordOrder> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(lordOrder::getId, Mid);
//        当前用户的所有订单
        lordOrder lordOrderServiceOne = lordOrderService.getOne(wrapper);
        LambdaQueryWrapper<OrderMessage> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderMessage::getMId, lordOrderServiceOne.getId());
        lordOrderServiceOne.setOrderMessages(orderMessageSrvice.list(queryWrapper));
        lordOrderServiceOne.setAddressMsg(userAddressService.getById(lordOrderServiceOne.getAddressId()));
        return Result.succeed(lordOrderServiceOne);
    }

    @GetMapping("/delete/{id}")
    public Boolean delete(@PathVariable Long id) {
        return orderMessageSrvice.removeById(id);
    }

    @PostMapping("/update")
    public Boolean update(@RequestBody OrderMessage orderMessage) {
        return orderMessageSrvice.updateById(orderMessage);
    }


}